package com.company.project.controller.ldjsc.weather;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.company.project.common.utils.DataResult;
import com.company.project.entity.ldjsc.weather.ZyCityCodeEntity;
import com.company.project.entity.ldjsc.weather.ZyWeatherRealtimeEntity;
import com.company.project.entity.ldjsc.weather.ZyWeatherSevenEntity;
import com.company.project.service.ldjsc.weather.ZyCityCodeService;
import com.company.project.service.ldjsc.weather.ZyWeatherRealtimeService;
import com.company.project.service.ldjsc.weather.ZyWeatherSevenService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.*;

@Controller
@Component
@RequestMapping("/sxzy/weather")
public class WeatherController {

    @Autowired
    private ZyWeatherRealtimeService zyWeatherRealtimeService;
    @Autowired
    private ZyCityCodeService zyCityCodeService;

    @Value("${tq.api-gaode.key}")
    private String keyGaode;
    @Value("${tq.api-gaode.url}")
    private String urlGaode;


    /**
     * 实时天气(只有市级调用高德接口2小时间隔测试环境不运行)
     *
     * @return
     */
    @GetMapping("/city/realtime")
    @ResponseBody
    public DataResult cityRealtime(String city) {

        LambdaQueryWrapper<ZyWeatherRealtimeEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.like(ZyWeatherRealtimeEntity::getCityName, city);
        queryWrapper.orderByDesc(ZyWeatherRealtimeEntity::getCreateDate);
        queryWrapper.last("limit 1");
        ZyWeatherRealtimeEntity zyWeatherSeven = zyWeatherRealtimeService.getOne(queryWrapper);
        return DataResult.success(zyWeatherSeven);
    }

    /**
     * 每2小时自动获取山西市级的实时天气
     */
    @Scheduled(cron = "0 0 0/2 * * ?")
    private void getCityCode() {

        //根据城市名获取城市代码（高德使用）
//        ZyCityCodeEntity zyCityCodeEntity = zyCityCodeService.selectNameByCode(city);
        //获取市级的城市编码
        LambdaQueryWrapper<ZyCityCodeEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ZyCityCodeEntity::getGrade, "1");
        List<ZyCityCodeEntity> list = zyCityCodeService.list(queryWrapper);

        try {
            for (ZyCityCodeEntity zyCityCodeEntity : list) {

                String requestUrl = urlGaode + "?key=" + keyGaode + "&city=" + zyCityCodeEntity.getCityCode() + "&extensions=base";

                URL url = new URL(requestUrl);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET");

                // 读取响应
                BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
                String line;
                StringBuilder response = new StringBuilder();

                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();

                // 解析 JSON
                JSONObject result = JSONObject.parseObject(response.toString());
                JSONArray lives = result.getJSONArray("lives");

                if (lives == null || lives.isEmpty()) {
                    throw new RuntimeException("未获取到天气数据");
                }

                JSONObject weather = lives.getJSONObject(0);

                ZyWeatherRealtimeEntity zyWeatherSeven = new ZyWeatherRealtimeEntity();
                zyWeatherSeven.setCityName(weather.getString("city"));
                zyWeatherSeven.setWeatherConditions(weather.getString("weather"));
                zyWeatherSeven.setCurrentTemperature(weather.getString("temperature"));
                zyWeatherSeven.setWind(weather.getString("winddirection"));
                zyWeatherSeven.setWindRating(weather.getString("windpower"));
                zyWeatherSeven.setAirHumidity(weather.getString("humidity"));
                zyWeatherRealtimeService.save(zyWeatherSeven);
                System.out.println("获取成功：" + zyWeatherSeven.getCityName() + "，时间：" + LocalDateTime.now() + "（实时）");
                //等待一秒
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    /**
     * 跳转到页面
     */
    @GetMapping("/index/zyWeatherSeven")
    public String zyWeatherSeven() {
        return "zyweatherseven/list";
    }


    @ApiOperation(value = "查询分页数据")
    @PostMapping("zyWeatherSeven/listByPage")
    @SaCheckPermission("zyWeatherSeven:list")
    @ResponseBody
    public DataResult findListByPage(@RequestBody ZyWeatherRealtimeEntity zyWeatherSeven) {
        LambdaQueryWrapper<ZyWeatherRealtimeEntity> queryWrapper = Wrappers.lambdaQuery();
        //查询条件示例
        queryWrapper.eq(zyWeatherSeven.getId() != null, ZyWeatherRealtimeEntity::getId, zyWeatherSeven.getId());
        queryWrapper.orderByDesc(ZyWeatherRealtimeEntity::getId);
        IPage<ZyWeatherRealtimeEntity> iPage = zyWeatherRealtimeService.page(zyWeatherSeven.getQueryPage(), queryWrapper);
        return DataResult.success(iPage);
    }


    @ApiOperation(value = "新增")
    @PostMapping("zyWeatherSeven/add")
    @SaCheckPermission("zyWeatherSeven:add")
    @ResponseBody
    public DataResult add(@RequestBody ZyWeatherRealtimeEntity zyWeatherSeven) {
        zyWeatherRealtimeService.save(zyWeatherSeven);
        return DataResult.success();
    }

    @ApiOperation(value = "删除")
    @DeleteMapping("zyWeatherSeven/delete")
    @SaCheckPermission("zyWeatherSeven:delete")
    @ResponseBody
    public DataResult delete(@RequestBody @ApiParam(value = "id集合") List<String> ids) {
        zyWeatherRealtimeService.removeByIds(ids);
        return DataResult.success();
    }

    @ApiOperation(value = "更新")
    @PutMapping("zyWeatherSeven/update")
    @SaCheckPermission("zyWeatherSeven:update")
    @ResponseBody
    public DataResult update(@RequestBody ZyWeatherRealtimeEntity zyWeatherSeven) {
        zyWeatherRealtimeService.updateById(zyWeatherSeven);
        return DataResult.success();
    }

}
